package com.wing.purchase.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.device.model.entity.DeviceBrand;
import com.wing.purchase.model.request.SupplierDetailConcatExcelInForm;
import com.wing.purchase.model.request.SupplierDetailExcelInForm;
import com.wing.purchase.model.response.SupplierContactsVO;
import com.wing.user.feign.UserClient;
import com.wing.user.model.request.User;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.purchase.model.entity.SupplierContacts;
import com.wing.purchase.model.request.SupplierContactsForm;
import com.wing.purchase.service.SupplierContactsService;
import com.wing.web.excel.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-供应商联系人表管理", tags = "#/purchase/supplierContacts")
@RestController("supplierContactsController")
@RequestMapping("purchase/admin/supplierContacts")
@RequiredArgsConstructor
@Slf4j
public class SupplierContactsController {

    private final SupplierContactsService supplierContactsService;

    @Resource
    UserClient userClient;

    @ApiOperation(value = "查询所有供应商联系人表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<SupplierContactsVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String corporateName
            ,String contactName
            ,String phoneNumber
            ,Integer corporateId
    ){

       /* Page<SupplierContacts> pg = new Page<>(page, limit);
        QueryWrapper<SupplierContacts> queryWrapper = new QueryWrapper<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }
        //搜索
        if (StringUtils.isNotBlank(corporateName)){
            queryWrapper.like("corporate_name",corporateName);
        }
        if (StringUtils.isNotBlank(contactName)){
            queryWrapper.like("contact_name",contactName);
        }
        if (StringUtils.isNotBlank(phoneNumber)){
            queryWrapper.like("phone_number",phoneNumber);
        }
        IPage<SupplierContacts> list = supplierContactsService.getBaseMapper().selectPage(pg, queryWrapper);
*/
        Page<SupplierContactsVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        //搜索
        if (StringUtils.isNotBlank(corporateName)){
            params.put("corporateName",corporateName);
        }
        if (StringUtils.isNotBlank(contactName)){
            params.put("contactName",contactName);
        }
        if (StringUtils.isNotBlank(phoneNumber)){
            params.put("phoneNumber",phoneNumber);
        }
        if (null!=corporateId){
            params.put("corporateId",corporateId);
        }
        IPage<SupplierContactsVO> list =  supplierContactsService.pageList4app(pg,params);

        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加供应商联系人表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(SupplierContactsForm.Add.class) SupplierContactsForm supplierContactsForm) {
        if (supplierContactsService.add(supplierContactsForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改供应商联系人表", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(SupplierContactsForm.Update.class) SupplierContactsForm supplierContactsForm) {
        SupplierContacts supplierContacts = supplierContactsService.getById(supplierContactsForm.getId());
        if(supplierContacts == null){
        return JsonResult.fail("修改失败！");
        }
        //修改用户
        User user = new User();
        user.setNickname(supplierContactsForm.getContactName());
        user.setOldPhone(supplierContacts.getPhoneNumber());
        user.setUsername(supplierContactsForm.getPhoneNumber());
        user.setPhone(supplierContactsForm.getPhoneNumber());
        userClient.updateThirdUser(user);

        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(SupplierContacts.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(supplierContactsForm, supplierContacts, copyOptions);
        if (supplierContactsService.updateById(supplierContacts)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除供应商联系人", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "supplierContactsId", value = "供应商联系人表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long supplierContactsId) {
        SupplierContacts supplierContacts = supplierContactsService.getById(supplierContactsId);
        //删除用户
        userClient.delThirdUser(supplierContacts.getPhoneNumber());
        if (supplierContactsService.removeById(supplierContactsId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }


    @ApiOperation(value = "删除供应商联系人", notes = "批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "供应商联系人id", required = true, dataType = "String", paramType = "query")
    })
    @PostMapping("/delBatch" )
    public JsonResult delete(String ids) {

        if (StringUtils.isNotBlank(ids)){
            List<Long> idList=new ArrayList<>();
            String[] idArray=ids.split(",");
            for (int i=0;i<idArray.length;i++){
                idList.add(Long.valueOf(idArray[i]));
            }
            if (supplierContactsService.remove(new QueryWrapper<SupplierContacts>().in("id",idList))) {
                return JsonResult.success("删除成功");
            }
        }else{
            return JsonResult.fail("请选择数量");
        }

        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "下载供应商联系人导入excel模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        supplierContactsService.template(response, request);
    }


    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("导入文件为空！");
        }
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            ExcelUtil<SupplierDetailConcatExcelInForm> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<SupplierDetailConcatExcelInForm> list = reader.read(is, SupplierDetailConcatExcelInForm.class);
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            supplierContactsService.importExcel(list);
        } catch (BusinessException e) {
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.exception("导入文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("导入成功！");
    }

}
